package com.srcbox.file.ui

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.Environment
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.CompoundButton
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import com.alibaba.fastjson.JSON
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo

import com.srcbox.file.R
import com.srcbox.file.data.AppInfo
import com.srcbox.file.data.AppSetting
import com.srcbox.file.util.*
import kotlinx.android.synthetic.main.app_show.*
import org.json.JSONObject
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipFile
import kotlin.math.roundToInt

class ShowApp : AppCompatActivity(), CompoundButton.OnCheckedChangeListener {
    private var appInfo: AppInfo? = null
    private var apkOutPath = ""
    private var getZipFile: GetZipFile? = null
    private var eggIo: EggIO? = null
    private var jsonStr = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.app_show)
        GlobalMethods(this).initActivityUi()

        initVar()
        initBeanLayout()
        initEvent()
        var isS = false
        folding_cell_2.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ ->
            if (!isS) {
                v.performClick()
            }
            isS = true
        }
        eggIo = EggIO()
//        AppSetting.extTablePath
        jsonStr = ""

        jsonStr = if (AppSetting.extTablePath.isEmpty()) {
            eggIo!!.readFile(assets.open("ext1.5.json"))
        } else {
            eggIo!!.readFile(AppSetting.extTablePath)
        }
        getZipFile = appInfo?.source?.let { GetZipFile(it, jsonStr) }
    }


    private fun initVar() {
        val bundle = intent.extras
        val packageName = bundle?.getString("packageName").toString()
        val applicationInfo = this.packageManager.getApplicationInfo(packageName, 0)
        val packageInfo = packageManager.getPackageInfo(packageName, 0)
        appInfo = AppInfo(
            applicationInfo.loadLabel(packageManager).toString(),
            packageInfo.versionName,
            applicationInfo.sourceDir,
            applicationInfo.loadIcon(packageManager),
            packageName
        )

        app_info_icon.setImageDrawable(appInfo?.icon)
        app_info_name.text = appInfo?.name
        app_info_version.text = appInfo?.version
        app_info_package.text = appInfo?.packageName
        var fp = AppSetting.fileStoragePath
        if (fp[fp.length - 1] != '/') {
            fp += "/"
        }

        apkOutPath = "$fp${appInfo?.name}/"
        apkOutPath += appInfo?.version + "/"

//        EggUtil.toast(this, apkOutPath)
    }

    @SuppressLint("SetTextI18n", "SimpleDateFormat")
    private fun initEvent() {

        folding_cell.setOnClickListener {
            folding_cell.toggle(false)
        }

        folding_cell_2.setOnClickListener {
            folding_cell_2.toggle(false)
        }

        show_get_src.setOnClickListener {
            if (show_get_src_text.text.toString().contains("提取中...")) {
                return@setOnClickListener
            }

            show_get_src_text.text = "提取中..."
            getAppSrc()
        }

        show_get_local_src.setOnClickListener {
            if (show_get_local_src_text.text.toString().contains("已提取")) {
                return@setOnClickListener
            }

            Thread {
                val p =
                    "${Environment.getExternalStorageDirectory()}/Android/data/${appInfo?.packageName}"
                val po = File(p)
//            val pSums = po.listFiles()?.size
                var isGet = false
                val getSrcFormDir = GetSrcFormDir(this, getZipFile!!) { i: Int, b: Boolean ->
                    isGet = b
                    runOnUiThread {
                        show_get_local_src_text.text = "已提取：${i}个"
                    }
                }
                getSrcFormDir.setOutDir("$apkOutPath/本地资源")
                getSrcFormDir.getSrc(po)
                runOnUiThread {
                    if (isGet && getSrcFormDir.fNum != 0) {
                        show_get_local_src_text.text = "提取本地资源"

                        YoYo.with(Techniques.FlipInY)
                            .duration(2000)
                            .onStart {
                                app_message.visibility = View.GONE
                                out_path.visibility = View.VISIBLE
                                out_path.text = "文件路径：${apkOutPath}本地资源"
                                EggUtil.toast(this, "提取成功，路径：${apkOutPath}本地资源")
                            }
                            .playOn(app_message_parent)

                    } else {
                        EggUtil.toast(this,"此应用无资源")
                        show_get_local_src_text.text = "提取本地资源"
                    }
                }
            }.start()
        }

        show_get_icon.setOnClickListener {

            val iconPath = "$apkOutPath${appInfo?.name}.png"
            EggUtil.saveBitmap(EggUtil.getBitmapFromDrawable(appInfo?.icon!!), File(iconPath))
            EggUtil.toast(this, "已保存到：$iconPath")
        }

        show_get_apk.setOnClickListener {
            if (show_get_src_text.text.toString().contains("提取中...")) {
                return@setOnClickListener
            }
            show_get_apk_text.text = "提取中..."
            Thread {
                val outPath = "$apkOutPath${appInfo?.name}.apk"
                val outPathFile = File(outPath)
                if (!outPathFile.parentFile!!.exists()) outPathFile.parentFile!!.mkdirs()
                EggIO().copyFileTo(
                    FileInputStream(appInfo?.source!!),
                    FileOutputStream(outPathFile)
                )
                runOnUiThread {
                    EggUtil.toast(this, "提取路径：$outPath")
                    show_get_apk_text.text = "提取APK"
                }
            }.start()
        }



        show_share_app.setOnClickListener {
            if (show_get_src_text.text.toString().contains("分享中...")) {
                return@setOnClickListener
            }
            show_share_app_text.text = "分享中...."
            Thread {
                EggUtil.shareFile(this, appInfo?.source.toString(), appInfo?.name.toString())
                runOnUiThread {
                    show_share_app_text.text = "分享软件"
                }
            }.start()

        }
    }

    private fun initBeanLayout() {

        EggUtil.loadIcon(this, icon_show_t1)
        EggUtil.loadIcon(this, icon_show_t1_c)
        EggUtil.loadIcon(this, icon_show_t2)
        EggUtil.loadIcon(this, icon_show_t2_c)

        val grad = GradientDrawable()
        val radii = FloatArray(8)
        radii[0] = 60f
        radii[1] = 60f
        radii[2] = 60f
        radii[3] = 60f
        radii[4] = 0f
        radii[5] = 0f
        radii[6] = 0f
        radii[7] = 0f
        grad.cornerRadii = radii
        grad.setStroke(1, Color.parseColor("#ffffff"))
        grad.setColor(Color.parseColor("#ffffff"))
        card_root.background = grad
        card_root.cardElevation = 10f


//        EggUtil.setViewRadius(show_get_src, "#ffffff", 1, "#ffffff", 360f)
        val layPar = mass_top.layoutParams as LinearLayout.LayoutParams
        layPar.topMargin = EggUtil.getStatusBarHeight(this)
        mass_top.layoutParams = layPar
        var extJson = ""
        extJson = if (!File(AppSetting.extTablePath).exists()) {
            EggIO().readFile(assets.open("ext1.5.json"))
        } else {
            EggIO().readFile(AppSetting.extTablePath)
        }
        var root = LinearLayout(this)
        JSON.parseObject(extJson).forEach {

            root = LinearLayout(this)
            val rootParams = WindowManager.LayoutParams()
            rootParams.width = LinearLayout.LayoutParams.MATCH_PARENT
            rootParams.height = LinearLayout.LayoutParams.WRAP_CONTENT
            root.layoutParams = rootParams
            root.gravity = Gravity.CENTER_VERTICAL

            root.setOnClickListener {
                return@setOnClickListener
            }

            val textV = TextView(this)
            textV.text = it.key
            textV.width = 0
            val textParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            textParams.gravity = Gravity.START
            textV.layoutParams = textParams
            val padSize = EggUtil.dp2px(this, 15f)
            textV.setPadding(padSize, padSize, padSize, padSize)
            textParams.weight = 1f
            root.addView(textV)

            val switchCompat = SwitchCompat(this)
            switchCompat.isChecked = JSON.parseObject(it.value.toString()).getBoolean("on")
            switchCompat.text = it.key
            switchCompat.textSize = 0f
            switchCompat.setOnCheckedChangeListener(this)
            EggUtil.setSwitchColor(switchCompat)
            root.addView(switchCompat)
            ext_root.addView(root)
        }
    }

    private fun getAppSrc() {
        YoYo.with(Techniques.FadeIn)
            .duration(2000)
            .repeat(0)
            .onStart {
                waveProgressView_parent.visibility = View.VISIBLE
            }
            .playOn(waveProgressView_parent)

        Thread {
            println(getZipFile)

            val zipFile = ZipFile(appInfo?.source)
            val zipFileNum = zipFile.size()
            getZipFile?.outputDir = apkOutPath
            var progressAfterTwo = 0.00
            getZipFile?.goExtractFile { i: Int, b: Boolean ->
                this.runOnUiThread {
                    if (b) {
                        slowShow(progressAfterTwo.toInt())
                    } else {
                        val progress = i.toDouble() / zipFileNum.toDouble() * 100.0
                        progressAfterTwo = ((progress * 100).roundToInt() / 100.0)
                        waveProgressView.progress = progressAfterTwo.toInt()
                    }
                }
            }
        }.start()
    }

    @SuppressLint("SetTextI18n")
    private fun slowShow(currentProgress: Int) {
        var currI = currentProgress
        Thread {
            while (currI != 100) {
                Thread.sleep(50)
                runOnUiThread {
                    waveProgressView.progress = currI
                    if (currI == 100) {
                        YoYo.with(Techniques.FlipInY)
                            .duration(2000)
                            .onStart {
                                app_message.visibility = View.GONE
                                out_path.visibility = View.VISIBLE
                                out_path.text = "文件路径：$apkOutPath"
                                EggUtil.toast(this, "提取成功，路径：$apkOutPath")
                                show_get_src_text.text = "提取资源"
                            }
                            .playOn(app_message_parent)
                    }
                }
                currI++
            }
        }.start()
    }


    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        val path = AppSetting.extTablePath
        val jsonO = JSONObject(EggIO().readFile(path))
        val thisJsonO = jsonO.getJSONObject(buttonView?.text.toString())
        thisJsonO.put("on", isChecked)
        val isOK = EggIO().writeFile(path, jsonO.toString())
        if (!isOK) {
            EggUtil.toast(this, "失败，请重试。")
        } else {
            jsonStr = if (AppSetting.extTablePath.isEmpty()) {
                eggIo!!.readFile(assets.open("ext1.5.json"))
            } else {
                eggIo!!.readFile(AppSetting.extTablePath)
            }
            getZipFile = appInfo?.source?.let { GetZipFile(it, jsonStr) }
        }
    }
}